<template>
  <div class="refund-list page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">售后列表</h1>
        <p class="page-subtitle">管理订单售后申请，处理退款相关事务</p>
      </div>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-input
          v-model="searchForm.orderNo"
          placeholder="订单编号"
          class="search-input"
          clearable
        >
          <template #prefix>
            <svg class="search-icon" viewBox="0 0 24 24" fill="currentColor">
              <path
                d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
              />
            </svg>
          </template>
        </el-input>
        <el-input
          v-model="searchForm.receiverName"
          placeholder="收货人"
          class="search-input"
          clearable
        />
        <el-input
          v-model="searchForm.receiverPhone"
          placeholder="收货人手机号"
          class="search-input"
          clearable
        />
        <el-select
          v-model="searchForm.refundStatus"
          placeholder="售后状态"
          clearable
          class="status-select"
        >
          <el-option label="申请中" :value="0" />
          <el-option label="退款成功" :value="1" />
          <el-option label="退款失败" :value="2" />
          <el-option label="退款中" :value="3" />
          <el-option label="已取消" :value="4" />
          <el-option label="拒绝" :value="5" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="refundList"
        style="width: 100%"
        class="refund-table"
        v-loading="loading"
        row-key="id"
        :expand-row-keys="expandedRows"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand" width="50">
          <template #default="{ row }">
            <div class="expand-content">
              <div class="expand-header">
                <h4>申请售后的商品列表</h4>
              </div>
              <el-table
                :data="row.orderItemDTOS"
                style="width: 100%"
                class="nested-table"
              >
                <el-table-column
                  prop="spuName"
                  label="商品名称"
                  width="200"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="skuSpecs"
                  label="规格"
                  width="380"
                  show-overflow-tooltip
                >
                  <template #default="{ row }">
                    <div v-if="row.skuSpecs">
                      <el-tag
                        v-for="(value, key) in JSON.parse(row.skuSpecs)"
                        :key="key"
                        size="small"
                        class="spec-tag"
                      >
                        {{ key }}: {{ value }}
                      </el-tag>
                    </div>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="skuNumber"
                  label="数量"
                  width="80"
                  align="center"
                />
                <el-table-column
                  prop="actualPrice"
                  label="订单金额"
                  width="100"
                  align="right"
                >
                  <template #default="{ row }">
                    <div class="amount-cell">
                      <div class="amount-value">
                        {{ formatCurrency(row.actualPrice) }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="refundedAmount"
                  label="已退款金额"
                  width="100"
                  align="right"
                >
                  <template #default="{ row }">
                    <div class="amount-cell">
                      <div class="amount-value">
                        {{ formatCurrency(row.refundedAmount) }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="refundStatus"
                  label="退款状态"
                  width="100"
                  align="center"
                >
                  <template #default="{ row }">
                    <el-tag
                      :type="getItemRefundStatusTagType(row.refundStatus)"
                      size="small"
                    >
                      {{ getItemRefundStatusText(row.refundStatus) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="商品图片" width="80" align="center">
                  <template #default="{ row }">
                    <el-image
                      v-if="row.skuImage"
                      :src="row.skuImage"
                      :preview-src-list="[row.skuImage]"
                      class="product-image"
                      fit="cover"
                    />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="refundNo"
          label="售后单号"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="orderNo"
          label="订单号"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="refundType"
          label="退款类型"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="row.refundType === 1 ? 'primary' : 'warning'"
              size="small"
            >
              {{ row.refundType === 1 ? "整单退款" : "部分退款" }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="refundReason"
          label="退款原因"
          width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ getRefundReasonText(row.refundReason) }}
          </template>
        </el-table-column> -->
        <el-table-column
          prop="refundDesc"
          label="退款说明"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="applyRefundAmount"
          label="申请退款金额"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            <div class="amount-cell">
              <div class="amount-value apply-amount">
                {{ formatCurrency(row.applyRefundAmount) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="refundAmount"
          label="实际退款金额"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            <div class="amount-cell">
              <div class="amount-value actual-amount">
                {{ formatCurrency(row.refundAmount) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="refundStatus"
          label="售后状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="getRefundStatusTagType(row.refundStatus)"
              size="small"
            >
              {{ getRefundStatusText(row.refundStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="receiverName"
          label="收货人"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="receiverPhone"
          label="收货人电话"
          width="130"
          show-overflow-tooltip
        />
        <el-table-column
          prop="applyTime"
          label="申请时间"
          width="160"
          show-overflow-tooltip
        />
        <el-table-column
          prop="processTime"
          label="受理时间"
          width="160"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.processTime">{{ row.processTime }}</span>
            <span v-else class="no-process">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="operatorName"
          label="受理人"
          width="100"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.operatorName">{{ row.operatorName }}</span>
            <span v-else class="no-operator">-</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="errorMsg"
          label="错误信息"
          width="160"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.errorMsg">{{ row.errorMsg }}</span>
            <span v-else class="no-error">-</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <!-- status=0: 显示同意和拒绝按钮 -->
              <template v-if="row.refundStatus === 0">
                <el-button
                  size="small"
                  type="success"
                  @click="processRefund(row)"
                  class="action-btn"
                >
                  同意
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="rejectRefund(row)"
                  class="action-btn"
                >
                  拒绝
                </el-button>
              </template>

              <!-- status=2: 显示重试和拒绝按钮 -->
              <template v-if="row.refundStatus === 2">
                <el-button
                  size="small"
                  type="primary"
                  @click="processRefund(row)"
                  class="action-btn"
                >
                  重试
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="rejectRefund(row)"
                  class="action-btn"
                >
                  拒绝
                </el-button>
              </template>

              <!-- status=1,3,4,5: 不显示操作按钮 -->
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 拒绝退款对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝退款"
      width="500px"
      @close="resetRejectForm"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">确定拒绝</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 退款金额输入对话框 -->
    <el-dialog
      v-model="refundAmountDialogVisible"
      title="输入退款金额"
      width="500px"
      @close="resetRefundAmountForm"
    >
      <el-form :model="refundAmountForm" label-width="120px">
        <el-form-item label="申请退款金额">
          <el-input
            :value="formatCurrency(refundAmountForm.applyAmount)"
            disabled
          />
        </el-form-item>
        <el-form-item label="实际退款金额" required>
          <el-input
            v-model="refundAmountForm.actualAmount"
            placeholder="请输入实际退款金额"
            @input="handleAmountInput"
          />
          <div class="amount-tip">金额必须大于0，保留两位小数</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="refundAmountDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRefundAmount"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { postWithAuth } from "@/utils/request";

// 类型定义
interface OrderItemDTO {
  id: string;
  orderId: string;
  spuName: string;
  skuSpecs: string;
  skuImage: string;
  skuNumber: number;
  actualPrice: number;
  refundedAmount: number;
  refundStatus: number;
}

interface RefundInfo {
  id: string;
  userId: string;
  orderId: string;
  orderItemId: string;
  orderNo: string;
  refundNo: string;
  refundType: number;
  refundReason: number;
  refundDesc: string;
  refundAmount: number | null;
  applyRefundAmount: number;
  refundStatus: number;
  applyTime: string;
  processTime: string | null;
  errorMsg: string | null;
  operatorName: string | null;
  remark: string;
  images: string | null;
  receiverName: string;
  receiverPhone: string;
  orderItemDTOS: OrderItemDTO[];
}

const loading = ref(false);
const refundList = ref<RefundInfo[]>([]);
const expandedRows = ref<string[]>([]);

// 搜索表单
const searchForm = ref({
  orderNo: "",
  refundStatus: "",
  receiverName: "",
  receiverPhone: "",
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 拒绝退款对话框
const rejectDialogVisible = ref(false);
const rejectForm = ref({
  refundId: "",
  reason: "",
});

// 退款金额输入对话框
const refundAmountDialogVisible = ref(false);
const refundAmountForm = ref({
  refundId: "",
  applyAmount: 0,
  actualAmount: "",
});

// 获取退款原因文本
// const getRefundReasonText = (reason: number): string => {
//   const reasonMap: Record<number, string> = {
//     1: "与商家协商一致退款",
//     2: "产品损坏/包装问题",
//     3: "快递还没有寄出",
//     4: "缺少物品/错过装运",
//     5: "价格下降/多付款",
//     6: "未按约定发运",
//     7: "其他",
//   };
//   return reasonMap[reason] || "未知原因";
// };

// 获取退款状态文本
const getRefundStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: "申请中",
    1: "退款成功",
    2: "退款失败",
    3: "退款中",
    4: "已取消",
    5: "拒绝",
  };
  return statusMap[status] || "未知状态";
};

// 获取退款状态标签类型
const getRefundStatusTagType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: "warning", // 申请中
    1: "success", // 退款成功
    2: "danger", // 退款失败
    3: "primary", // 退款中
    4: "info", // 已取消
    5: "danger", // 拒绝
  };
  return typeMap[status] || "info";
};

// 获取商品退款状态文本
const getItemRefundStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: "无退款",
    1: "退款中",
    2: "已退款",
  };
  return statusMap[status] || "未知状态";
};

// 获取商品退款状态标签类型
const getItemRefundStatusTagType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: "info", // 无退款
    1: "warning", // 退款中
    2: "success", // 已退款
  };
  return typeMap[status] || "info";
};

// 格式化金额
const formatCurrency = (amount: number | null): string => {
  if (amount === null || amount === undefined) return "-";
  const num = Number(amount);
  if (Number.isNaN(num)) return "-";
  return `¥${num.toFixed(2)}`;
};

// 处理退款（同意或重试）
const processRefund = (row: RefundInfo) => {
  refundAmountForm.value.refundId = row.id;
  refundAmountForm.value.applyAmount = row.applyRefundAmount;
  refundAmountForm.value.actualAmount = "";
  refundAmountDialogVisible.value = true;
};

// 处理金额输入
const handleAmountInput = (value: string) => {
  // 移除所有非数字和小数点的字符
  let cleanValue = value.replace(/[^\d.]/g, "");

  // 确保只有一个小数点
  const parts = cleanValue.split(".");
  if (parts.length > 2) {
    cleanValue = parts[0] + "." + parts.slice(1).join("");
  }

  // 限制小数点后最多两位
  if (parts.length === 2 && parts[1].length > 2) {
    cleanValue = parts[0] + "." + parts[1].substring(0, 2);
  }

  // 更新表单值
  refundAmountForm.value.actualAmount = cleanValue;
};

// 确认退款金额
const confirmRefundAmount = async () => {
  const amount = parseFloat(refundAmountForm.value.actualAmount);

  if (!refundAmountForm.value.actualAmount || isNaN(amount) || amount <= 0) {
    ElMessage.warning("请输入有效的退款金额，金额必须大于0");
    return;
  }

  try {
    const response = await postWithAuth("/internal/order/processOrderRefund", {
      refundId: refundAmountForm.value.refundId,
      refundAmount: amount,
      processCode: "agree",
    });

    if (response.code === 0) {
      ElMessage.success("退款处理成功");
      refundAmountDialogVisible.value = false;
      fetchRefundList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("处理退款失败:", error);
    ElMessage.error("操作失败");
  }
};

// 重置退款金额表单
const resetRefundAmountForm = () => {
  refundAmountForm.value = {
    refundId: "",
    applyAmount: 0,
    actualAmount: "",
  };
};

// 获取售后列表
const fetchRefundList = async () => {
  loading.value = true;
  try {
    const params = {
      orderNo: searchForm.value.orderNo || "",
      refundStatus: searchForm.value.refundStatus || "",
      receiverName: searchForm.value.receiverName || "",
      receiverPhone: searchForm.value.receiverPhone || "",
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
    };

    const res = await postWithAuth("/internal/order/orderRefundPage", params);
    if (res.code === 0 && res.data) {
      refundList.value = Array.isArray(res.data.list) ? res.data.list : [];
      total.value = Number(res.data.total || 0);
    } else {
      refundList.value = [];
      total.value = 0;
      ElMessage.error(res.message || "获取售后列表失败");
    }
  } catch (error) {
    console.error("获取售后列表失败:", error);
    ElMessage.error("获取售后列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchRefundList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    orderNo: "",
    refundStatus: "",
    receiverName: "",
    receiverPhone: "",
  };
  currentPage.value = 1;
  fetchRefundList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchRefundList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchRefundList();
};

// 展开行变化
const handleExpandChange = (_row: RefundInfo, _expandedRows: any) => {
  // 可以在这里处理展开逻辑
};

// 拒绝退款
const rejectRefund = (row: RefundInfo) => {
  rejectForm.value.refundId = row.id;
  rejectForm.value.reason = "";
  rejectDialogVisible.value = true;
};

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.value.reason.trim()) {
    ElMessage.warning("请输入拒绝原因");
    return;
  }

  try {
    const response = await postWithAuth("/internal/order/processOrderRefund", {
      refundId: rejectForm.value.refundId,
      refuseReason: rejectForm.value.reason,
      processCode: "refuse",
    });

    if (response.code === 0) {
      ElMessage.success("退款申请已拒绝");
      rejectDialogVisible.value = false;
      fetchRefundList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("拒绝退款失败:", error);
    ElMessage.error("操作失败");
  }
};

// 重置拒绝表单
const resetRejectForm = () => {
  rejectForm.value = {
    refundId: "",
    reason: "",
  };
};

onMounted(() => {
  fetchRefundList();
});
</script>

<style scoped>
.refund-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #f3f4f6;
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 200px;
}

.status-select {
  width: 150px;
}

.search-icon {
  width: 16px;
  height: 16px;
  color: #9ca3af;
}

.refund-table {
  margin: 0;
}

.expand-content {
  padding: 20px;
  background-color: #f9fafb;
}

.expand-header {
  margin-bottom: 16px;
}

.expand-header h4 {
  margin: 0;
  color: #374151;
  font-size: 16px;
  font-weight: 600;
}

.nested-table {
  background: white;
  border-radius: 6px;
  overflow: hidden;
}

.spec-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.product-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.amount-cell {
  text-align: right;
}

.amount-value {
  font-weight: 600;
  color: #1f2937;
}

.apply-amount {
  color: #f59e0b;
}

.actual-amount {
  color: #10b981;
}

.no-process,
.no-operator {
  color: #9ca3af;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-btn {
  margin: 0;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f3f4f6;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 12px;
}

.amount-tip {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 4px;
}
</style>
